local lib = require "async-lib"
function run(code)
	-- coroutine.wrap和coroutine.create一样创建协程，不同的是它返回一个函数，调用这个函数
	-- 就启动协程
	local co = coroutine.wrap(function()
		code()	-- 执行传进来的代码
		lib.stop() -- 完成事件
	end)
	co() -- 开始协程执行
	lib.runloop() -- 开始事件循环
end

function putline(stream, line)
	local co = coroutine.running()
	local callback = (function()
		coroutine.resume(co)
	end)
	lib.writeline(stream, line, callback)
	coroutine.yield()
end

function getline(stream)
	local co = coroutine.running()
	local callback = (function(line)
		coroutine.resume(co, line)
	end)
	lib.readline(stream, callback)
	local line = coroutine.yield()
	return line
end

run(function()
	local t = {}
	local inp = io.input()
	local out = io.output()
	while true do
		local line = getline(inp)
		if not line or line == "stop" then
			break
		end
		t[#t + 1] = line
	end

	for i = #t, 1, -1 do
		putline(out, t[i]..'\n')
	end
end)
